package com.yangliu.darkbow.main;

import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.core.JreMemoryLeakPreventionListener;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.core.ThreadLocalLeakPreventionListener;
import org.apache.catalina.mbeans.GlobalResourcesLifecycleListener;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.VersionLoggerListener;

import java.io.File;
import java.util.Optional;

/**
 * Created by yangliu on 2017/5/4.
 */
public class TomcatMain {
    public static final Optional<String> port = Optional.ofNullable(System.getenv("PORT"));

    public static void main(String[] args) throws Exception {
        String contextPath = "";
        String baseDir =  new File("").getAbsolutePath()+"/app/src/main/webapp";
        Tomcat tomcat = new Tomcat();
        // Add AprLifecycleListener
        StandardServer server = (StandardServer) tomcat.getServer();
        AprLifecycleListener listener = new AprLifecycleListener();
        server.addLifecycleListener(listener);
        VersionLoggerListener versionLoggerListener = new VersionLoggerListener();
        server.addLifecycleListener(versionLoggerListener);
        JreMemoryLeakPreventionListener jreMemoryLeakPreventionListener = new JreMemoryLeakPreventionListener();
        server.addLifecycleListener(jreMemoryLeakPreventionListener);
        GlobalResourcesLifecycleListener globalResourcesLifecycleListener = new GlobalResourcesLifecycleListener();
        server.addLifecycleListener(globalResourcesLifecycleListener);
        ThreadLocalLeakPreventionListener threadLocalLeakPreventionListener = new ThreadLocalLeakPreventionListener();
        server.addLifecycleListener(threadLocalLeakPreventionListener);

        tomcat.setPort(Integer.valueOf(port.orElse("8080") ));
        tomcat.getHost().setAppBase(".");
        tomcat.addWebapp(contextPath, baseDir);
        tomcat.start();
        tomcat.getServer().await();
    }
}
